<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { getListApi, delListApi, fishingtApi, allocationApi, getFieldEnumApi } from '@/api/customer'
import { getListApi as getOperatorListApi } from '@/api/operator'
import { CurdData, FieldEnum, SchemaConfig } from '@/api/customer/types'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useEventBus } from '@/hooks/event/useEventBus'
import { useCrudSchemas, AllSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { ElMessage, ElMessageBox } from 'element-plus'
import useSchema from './components/hooks/useSchema'
import { ActionButtonsTemplate, SelectOption } from '@/api/global/types'
import { TableDialog } from '@/components/Dialog'
import { useTableDialogStore } from '@/store/modules/tableDialog'
import { CrudSchema } from '@/hooks/web/useCrudSchemas'
import { getSelectListApi as getCountrySelectListApi } from '@/api/regionCountry'
import { getSelectListApi as getOperatorSelectListApi } from '@/api/operator'

defineOptions({
  name: 'CustomerPage'
})

const { t } = useI18n()

const tableDialogStoreID = 'customerPage'
const itemTitleName = 'cname'
const tableDialogStore = useTableDialogStore(tableDialogStoreID)
tableDialogStore.limit = 1
// 定义表格对话框的 CRUD 模式
const tableDialogCurdSchema = reactive<CrudSchema[]>([
  {
    field: 'selection',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: t('operator.index'),
    type: 'index',
    search: {
      hidden: true
    }
  },
  {
    field: 'cname',
    label: t('operator.cname'),
    search: {
      component: 'Input'
    }
  },
  {
    field: 'phone',
    label: t('operator.phone'),
    form: {
      component: 'Input',
      formItemProps: {}
    }
  },
  {
    field: 'email',
    label: t('operator.email'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'department.name',
    label: t('operator.department'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    }
  },
  {
    field: 'job_txt',
    label: t('operator.job'),
    search: {
      hidden: true
    },
    form: {
      component: 'Input'
    }
  }
])
const { allSchemas: tableDialogSchemas } = useCrudSchemas(tableDialogCurdSchema)
tableDialogStore.setSchema(tableDialogSchemas)

const { push } = useRouter()

const ids = ref<string[]>([])

const searchParams = ref({})
const setSearchParams = (params: any) => {
  currentPage.value = 1
  searchParams.value = params
  getList()
}

const { tableRegister, tableState, tableMethods } = useTable({
  currentPageSize: 15,
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState

    const res = await getListApi({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      attr: 2, // 1: 私海 2: 公海
      ...unref(searchParams)
    })
    return {
      list: res.data.list,
      total: res.data.total
    }
  },
  fetchDelApi: async () => {
    const res = await delListApi(unref(ids).join(','))
    return !!res
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

getList()

useEventBus({
  name: 'getList',
  callback: (type: string) => {
    if (type === 'add') {
      currentPage.value = 1
    }
    getList()
  }
})

// Begin CRUD Template Block
// ------------------------
let allocationId = 0
const allocationDataAction = async (row: CurdData | null) => {
  if (!row) {
    ElMessage.error(t('common.selectData'))
    return
  }
  ElMessageBox.confirm(
    t('confirmMessage.customer.allocationMessage'),
    t('confirmMessage.warning'),
    {
      confirmButtonText: t('confirmMessage.ok'),
      cancelButtonText: t('confirmMessage.cancel'),
      type: 'warning'
    }
  ).then(async () => {
    allocationId = row.id
    tableDialogStore.openDialog()
  })
}

const fishingData = async (row: CurdData | null) => {
  ElMessageBox.confirm(t('confirmMessage.customer.fishingMessage'), t('confirmMessage.warning'), {
    confirmButtonText: t('confirmMessage.ok'),
    cancelButtonText: t('confirmMessage.cancel'),
    type: 'warning'
  }).then(async () => {
    const res = await fishingtApi({
      id: row?.id
    })
    if (res) {
      ElMessage.success(t('confirmMessage.customer.fishingSuccess'))
      getList()
    }
  })
}

const delData = async (row: CurdData | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: CurdData) => v.id) || []

  if (ids.value.length === 0) {
    ElMessage.error(t('common.selectData'))
    return
  }
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = (row: CurdData, type: string) => {
  push(`/customer/customerList/${type}?id=${row.id}&source=/public-page`)
}

const actionButtonsTemplate: ActionButtonsTemplate = {
  length: 5,
  template: (data: any) => {
    return (
      <>
        <BaseButton type="primary" size="small" onClick={() => allocationDataAction(data.row)}>
          {t('action.customer.allocation')}
        </BaseButton>
        <BaseButton type="info" size="small" onClick={() => fishingData(data.row)}>
          {t('action.customer.fishing')}
        </BaseButton>
        <BaseButton size="small" onClick={() => action(data.row, 'edit')}>
          {t('action.edit')}
        </BaseButton>
        <BaseButton type="success" size="small" onClick={() => action(data.row, 'detail')}>
          {t('action.detail')}
        </BaseButton>
      </>
    )
  }
}

const allSchemas = ref<AllSchemas>({
  searchSchema: [], // 确保与接口匹配
  tableColumns: [], // 确保与接口匹配
  formSchema: [], // 确保与接口匹配
  detailSchema: [] // 确保与接口匹配
})
// 根据实际数据初始化
let customerFieldEnum: FieldEnum = {}
const getFieldEnum = async () => {
  const res = await getFieldEnumApi({ field: 'all' })
  customerFieldEnum = res.data
}

let countrySelectOptions: SelectOption[] = []
const getCountrySelectList = async () => {
  const res = await getCountrySelectListApi({})
  countrySelectOptions = res.data.list
}
let operatorOptions: SelectOption[] = []
const getOperatorSelectList = async () => {
  const res = await getOperatorSelectListApi({})
  operatorOptions = res.data.list
}
const fetchData = async () => {
  await getFieldEnum()
  await getCountrySelectList()
  await getOperatorSelectList()

  const schemaConfig: any = {
    actionButtonsTemplate,
    operatorOptions,
    fieldEnum: customerFieldEnum,
    fromPage: 'public',
    countrySelectOptions: countrySelectOptions
  }
  const { crudSchemas } = useSchema(schemaConfig)
  const { allSchemas: newSchemas } = useCrudSchemas(crudSchemas)

  // 合并新的数据，确保不改变原有数据的类型
  allSchemas.value = {
    searchSchema: newSchemas.searchSchema || [],
    tableColumns: newSchemas.tableColumns || []
  }
}
fetchData()
// End CRUD Template Block
// ------------------------

const AddAction = () => {
  push('/customer/customerList/add?source=/public-page')
}

const delLoading = ref(false)

const tableDialogSubmit = async (selectData: Array<Object>) => {
  const selectDataId = selectData.map((v: any) => v.id).join(',')
  if (!selectDataId || !allocationId) {
    ElMessage.error(t('common.selectData'))
    return
  }

  const res = await allocationApi({
    id: selectDataId,
    allocationId: allocationId
  })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (res) {
    ElMessage.success(t('confirmMessage.customer.allocationSuccess'))
    getList()
  }
}

// 清空 store 数据
// onBeforeUnmount(() => {
//   tableDialogStore.reset()
//   allocationId = 0
// })
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />

    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('action.add') }}</BaseButton>
      <!-- <BaseButton :loading="delLoading" type="danger" @click="delData(null)">
        {{ t('action.del') }}
      </BaseButton> -->
    </div>

    <Table
      showAction
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
    />

    <TableDialog
      :getListApi="getOperatorListApi"
      :limit="tableDialogStore.limit"
      :tableDialogStoreID="tableDialogStoreID"
      :itemTitleName="itemTitleName"
      @submit="tableDialogSubmit"
    />
  </ContentWrap>
</template>
@/hooks/event/useEventBus
